// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Storage from 'vue-ls'
import App from './App'
import router from './router'
import mavonEditor from 'mavon-editor'
import store from './store'
import ElementUI from 'element-ui'
import request from './utils/request'
import config from '@/defaultSettings'
import 'element-ui/lib/theme-chalk/index.css'
import 'mavon-editor/dist/css/index.css'

// 设置反向代理，前端请求默认发送到 http://localhost:8443/api
var axios = require('axios')
// axios.defaults.baseURL = 'http://localhost:9080/api'
axios.defaults.baseURL = 'http://localhost:9090/api'
axios.defaults.withCredentials = true
// 全局注册，之后可在其他组件中通过 this.$axios 发送数据
Vue.prototype.$axios = axios
Vue.config.productionTip = false

Vue.use(ElementUI)
Vue.use(mavonEditor)
Vue.use(Storage, config.storageOptions)

router.beforeEach((to, from, next) => {
  // debugger
  if (Vue.ls.get('Access-Token') && to.path.startsWith('/admin')) {
    initAdminMenu(router, store)
  }
  // 已登录状态下访问 login 页面直接跳转到后台首页
  if (Vue.ls.get('Access-Token') && to.path.startsWith('/login')) {
    next({
      name: 'Dashboard'
    })
  }
  if (to.meta.requireAuth) {
    if (store.state.user.userName) {
      axios.get('/authentication').then(resp => {
        if (resp) next()
      })
    } else {
      next({
        path: 'login',
        query: {redirect: to.fullPath}
      })
    }
  } else {
    next()
  }
})

const formatRoutes = (routes) => {
  let fmtRoutes = []
  routes.forEach(route => {
    if (route.children) {
      route.children = formatRoutes(route.children)
    }
    let fmtRoute = {
      path: route.path,
      component: resolve => {
        require(['./components/admin/' + route.component + '.vue'], resolve)
      },
      name: route.name,
      nameZh: route.nameZh,
      iconCls: route.iconCls,
      children: route.children
    }
    fmtRoutes.push(fmtRoute)
  })
  return fmtRoutes
}

const initAdminMenu = (router, store) => {
  if (store.state.adminMenus && store.state.adminMenus.length > 0) {
    return
  }
  axios.get('/admin/role/menu').then(resp => {
    if (resp && resp.status === 200) {
      if (resp.data && resp.data.code === 1000) {
        var fmtRoutes = formatRoutes(resp.data.data)
        router.addRoutes(fmtRoutes)
        store.commit('initAdminMenu', fmtRoutes)
      }
    }
  })
}

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  mounted () {
    store.commit('SET_TOKEN', Vue.ls.get('Access-Token'))
  },
  template: '<App/>'
})
